package com.mall.pay.services;

import com.mall.commons.tool.exception.ValidateException;
import com.mall.order.OrderCoreService;
import com.mall.order.OrderQueryService;
import com.mall.order.constant.OrderRetCode;
import com.mall.order.dto.PayOrderSuccessRequest;
import com.mall.order.dto.PayOrderSuccessResponse;
import com.mall.pay.PayCoreService;
import com.mall.pay.biz.payment.constants.PayResultEnum;
import com.mall.pay.constants.PayReturnCodeEnum;
import com.mall.pay.dal.entitys.Payment;
import com.mall.pay.dal.persistence.PaymentMapper;
import com.mall.pay.dto.PaymentRequest;
import com.mall.pay.dto.alipay.AlipayQueryRetResponse;
import com.mall.pay.dto.alipay.AlipaymentResponse;
import com.mall.pay.dto.wechat.WechatPaymentResopnse;
import com.mall.pay.utils.ExceptionProcessorUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.dubbo.config.annotation.Reference;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import tk.mybatis.mapper.entity.Example;

import java.math.BigDecimal;
import java.util.Date;


@Slf4j
@Service(cluster = "failover",timeout = 2000)
public class PayCoreServiceImpl implements PayCoreService {

    @Autowired
    PayHelper helper;
    @Autowired
    PaymentMapper paymentMapper;

    @Reference(check = false)
    OrderCoreService orderCoreService;

    @Reference
    OrderQueryService orderQueryService;

    @Override
    public AlipaymentResponse aliPay(PaymentRequest request) {
        AlipaymentResponse alipaymentResponse = new AlipaymentResponse();
        //必要参数校验
        try {
            request.requestCheck();
        }catch (Exception e){
            log.info(e.getMessage());
            alipaymentResponse.setCode(PayReturnCodeEnum.REQUISITE_PARAMETER_NOT_EXIST.getCode());
            alipaymentResponse.setMsg(PayReturnCodeEnum.REQUISITE_PARAMETER_NOT_EXIST.getMsg());
            return alipaymentResponse;
        }

        alipaymentResponse.setCode(PayReturnCodeEnum.SUCCESS.getCode());
        alipaymentResponse.setMsg(PayReturnCodeEnum.SUCCESS.getMsg());
        String code = helper.getCode(request);
        if (code == null) {
          // 获取二维码失败
            alipaymentResponse.setCode(PayReturnCodeEnum.GET_CODE_FALIED.getCode());
            alipaymentResponse.setMsg(PayReturnCodeEnum.GET_CODE_FALIED.getMsg());
            return alipaymentResponse;
        }

        Payment payment = generatePayment(request);
        alipaymentResponse.setQrCode(code);

        try {
            paymentMapper.insert(payment);
        } catch (Exception e) {
            log.error("PayCoreServiceImpl.aliPay occurs error: " + e);
            ExceptionProcessorUtils.wrapperHandlerException(alipaymentResponse, e);
        }

        return alipaymentResponse;

    }

    private Payment generatePayment(PaymentRequest request) {
        Payment payment = new Payment();
        payment.setCreateTime(new Date());
        payment.setOrderId(request.getTradeNo());
        BigDecimal orderFee = request.getOrderFee();
        payment.setOrderAmount(orderFee);
        payment.setPayerAmount(orderFee);
        payment.setPayWay("支付宝");
        payment.setProductName(request.getSubject());
        payment.setPayWay(request.getPayChannel());
        payment.setPayerUid(request.getUserId());
        payment.setPayerName("xrj");
        payment.setStatus(PayResultEnum.TRADE_PROCESSING.getCode());
        payment.setRemark("支付宝支付");
        payment.setUpdateTime(new Date());
        return payment;
    }

    @Override
    public AlipayQueryRetResponse queryAlipayRet(String orderId) {

        AlipayQueryRetResponse response = new AlipayQueryRetResponse();
        try {
            if(StringUtils.isBlank(orderId)){
                throw new ValidateException(PayReturnCodeEnum.REQUISITE_PARAMETER_NOT_EXIST.getCode(),PayReturnCodeEnum.REQUISITE_PARAMETER_NOT_EXIST.getMsg());
            }

            boolean payStatus = helper.queryTrade(orderId);
            //修改订单状态为已付款
            if(payStatus) {
                PayOrderSuccessRequest payOrderSuccessRequest = new PayOrderSuccessRequest();
                payOrderSuccessRequest.setOrderId(orderId);
                PayOrderSuccessResponse payOrderSuccessResponse = orderCoreService.payOrderSuccess(payOrderSuccessRequest);
                if (!payOrderSuccessResponse.getCode().equals(OrderRetCode.SUCCESS.getCode())) {
                    response.setCode(OrderRetCode.DB_SAVE_EXCEPTION.getCode());
                    response.setMsg(OrderRetCode.DB_SAVE_EXCEPTION.getMessage());
                    return response;
                }
                Example example = new Example(Payment.class);
                example.createCriteria().andEqualTo("orderId", orderId);
                Payment payment = paymentMapper.selectOneByExample(example);
                payment.setStatus(PayResultEnum.TRADE_SUCCESS.getCode());
                Date now = new Date();
                payment.setCompleteTime(now);
                payment.setUpdateTime(now);
                payment.setPaySuccessTime(now);
                int updatePay = paymentMapper.updateByPrimaryKeySelective(payment);
                if (updatePay == 0) {
                    response.setCode(OrderRetCode.DB_SAVE_EXCEPTION.getCode());
                    response.setMsg(OrderRetCode.DB_SAVE_EXCEPTION.getMessage());
                }
                response.setCode(PayReturnCodeEnum.SUCCESS.getCode());
                response.setMsg(PayReturnCodeEnum.SUCCESS.getMsg());
            }else {
                response.setCode(PayReturnCodeEnum.ORDER_HAD_NOT_PAY.getCode());
                response.setMsg(PayReturnCodeEnum.ORDER_HAD_NOT_PAY.getMsg());
            }
        } catch (Exception e) {
            log.error("PayCoreServiceImpl.queryAlipayRet occurs error: " + e);
            ExceptionProcessorUtils.wrapperHandlerException(response, e);
        }
        return response;
    }



    @Override
    public WechatPaymentResopnse wxPay(PaymentRequest paymentRequest) {
        return null;
    }
}
